import { useUserStore } from "@/stores/userStore";
import router from "@/router";
import axios from "axios";
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
const request = axios.create({
    baseURL: "http://pcapi-xiaotuxian-front-devtest.itheima.net",
    timeout: 5000
})



//axios 请求拦截器
request.interceptors.request.use(config => {
    // 1. 从pinia获取token数据
    const userStore = useUserStore()
    const token = userStore.userInfo.token
    if (token) {
        // 2. 按照后端的要求拼接token数据
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, error => Promise.reject(error))

//axiois 响应拦截器
request.interceptors.response.use(res => res.data, error => {
    const userStore = useUserStore()
    //统一错误提示
    ElMessage({
        type: 'error',
        message: error.response.data.message
    })
    //401 token失效处理
    if (error.response.status == 401) {
        userStore.clearUserInfo()
        router.push('/login')
    }
    return Promise.reject(error)
})


export default request